import React, { useEffect, useState } from "react";
import {
    Button,
    Card,
    Col,
    Input,
    message,
    Modal,
    Row,
    Space,
    Spin,
    Table,
} from "antd";
import { useRequest } from "ahooks";
import dayjs from "dayjs";
import UserForm from "../../components/UserForm";

type Props = {};

async function fetchUser() {
    const res = await fetch("/api/user");
    return res.json();
}

const User: React.FC<Props> = (props) => {
    const [messageApi, contextHolder] = message.useMessage();
    const [name, setName] = useState<string>("");
    const [email, setEmail] = useState<string>("");
    const [edit, setEditData] = useState<{ name: string; email: string }>();
    const [visible, setVisible] = useState<boolean>(false);
    const [type, setType] = useState<"add" | "edit">("add");
    const { data, loading, error, run } = useRequest(() => fetchUser());
    const { confirm } = Modal;

    const handleOnCreate = () => {
        setVisible(() => {
            setType("add");
            return true;
        });
    };

    const handleOnEdit = (record: any) => {
        console.log(record);

        setVisible(() => {
            setType("edit");
            setEditData({
                name: record.name,
                email: record.email,
            });
            return true;
        });
    };

    const handleOnClear = () => {
        setName("");
        setEmail("");
    };

    const handleOnDelete = (id: number) => {
        confirm({
            title: "警告",
            content: "确定删除吗?",
            okText: "确定",
            cancelText: "取消",
            async onOk() {
                // 用fetch的delete调用接口/api/user/delete
                const result = await fetch(`/api/user/delete/${id}`, {
                    method: "DELETE",
                });
                if (result.ok) {
                    message.success({
                        type: "success",
                        content: "删除成功",
                    });
                    run();
                } else {
                    message.success({
                        type: "error",
                        content: "删除失败",
                    });
                }
            },
        });
    };

    const handleOnOk = async (value: any) => {
        // 用fetch的post调用接口/api/user/create
        const result = await fetch("/api/user/create", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify(value),
        });
        if (result.ok) {
            message.success({
                type: "success",
                content: "创建成功",
            });
            run();
            setVisible(false);
        }
    };

    const handleOnCancel = () => {
        setVisible(false);
    };

    const columns = [
        {
            title: "ID",
            dataIndex: "id",
            key: "id",
        },
        {
            title: "姓名",
            dataIndex: "name",
            key: "name",
        },
        {
            title: "邮箱",
            dataIndex: "email",
            key: "email",
        },
        {
            title: "创建时间",
            dataIndex: "created_at",
            render: (_, record) => (
                <div key={record.id}>
                    {dayjs.tz(record.createdAt).format("YYYY-MM-DD HH:mm:ss")}
                </div>
            ),
        },
        {
            title: "操作",
            dataIndex: "action",
            render: (_, record) => {
                return (
                    <Space size={"middle"} key={record.id}>
                        <Button type="primary" onClick={() => handleOnEdit(record)}>
                            修改
                        </Button>
                        <Button
                            type="primary"
                            danger
                            onClick={() => handleOnDelete(record.id)}
                        >
                            删除
                        </Button>
                    </Space>
                );
            },
        },
    ];

    if (error) {
        messageApi.error({
            content: error.message,
        });
    }
    return (
        <>
            <div>
                <Card title={"用户中心"}>
                    <Space direction="vertical" style={{ width: "100%" }} size="large">
                        <Row gutter={16} justify={"start"}>
                            <Col span={5}>
                                <Space size={"small"}>
                                    <label htmlFor="name">用户名: </label>
                                    <Input
                                        id="name"
                                        placeholder="请输入用户名"
                                        value={name}
                                        onChange={(e) => setName(e.target.value)}
                                    />
                                </Space>
                            </Col>
                            <Col span={5}>
                                <Space>
                                    <label htmlFor="email">邮箱: </label>
                                    <Input
                                        id="email"
                                        placeholder="请输入邮箱"
                                        value={email}
                                        onChange={(e) => setEmail(e.target.value)}
                                    />
                                </Space>
                            </Col>
                            <Col span={6}>
                                <Space>
                                    <Button type="primary" onClick={handleOnCreate}>
                                        新建
                                    </Button>
                                    <Button type="primary" danger onClick={handleOnClear}>
                                        清空
                                    </Button>
                                </Space>
                            </Col>
                        </Row>
                        <Row gutter={24}>
                            <Col span={24}>
                                <Spin tip={"Loading"} spinning={loading}>
                                    <Table
                                        loading={loading}
                                        dataSource={data?.data}
                                        columns={columns}
                                        rowKey={(record) => record.id}
                                    ></Table>
                                </Spin>
                            </Col>
                        </Row>
                    </Space>
                </Card>
            </div>
            <UserForm
                visable={visible}
                data={edit}
                handleOnOk={handleOnOk}
                handleOnCancel={handleOnCancel}
                type={type}
            />
        </>
    );
};

export default User;
